﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class GPUTerrainTools : MonoBehaviour
{
    
    [MenuItem("Local/SaveTerrainInfo")]
    public static void SaveHeightMapAndNormalMap()
    {
        Terrain terrain = Terrain.activeTerrain;
        var heightmapTex = terrain.terrainData.heightmapTexture;
        SaveTexture(heightmapTex, TextureFormat.RFloat, Application.dataPath + "/GPUDrivenTerrain/HeightMap.png");

        var normalTex = new Texture2D(heightmapTex.width, heightmapTex.height, TextureFormat.RGBA32, -1, true);
        var colors = new Color[heightmapTex.width * heightmapTex.width];
        for (int j = 0; j < heightmapTex.height; ++j)
        {
            for (int i = 0; i < heightmapTex.width; ++i)
            {
                var normal = terrain.terrainData.GetInterpolatedNormal((float)i / heightmapTex.width, (float)j / heightmapTex.height);
                colors[j * heightmapTex.width + i] = new Color(normal.z * 0.5f + 0.5f, normal.y * 0.5f + 0.5f, normal.x * 0.5f + 0.5f);
            }
        }
        normalTex.SetPixels(colors);
        normalTex.Apply();
        SaveTexture(normalTex, Application.dataPath + "/GPUDrivenTerrain/NormalMap.png");
    }

    public static Texture2D ToTexture2D(RenderTexture rTex, TextureFormat saveFormat)
    {
        Texture2D tex = new Texture2D(rTex.width, rTex.height, saveFormat, false);
        var orig = RenderTexture.active;
        RenderTexture.active = rTex;
        tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
        tex.Apply();
        RenderTexture.active = orig;
        return tex;
    }

    public static void SaveTexture(RenderTexture rTex, TextureFormat saveFormat, string path)
    {
        byte[] bytes = ToTexture2D(rTex, saveFormat).EncodeToPNG();
        System.IO.File.WriteAllBytes(path, bytes);

        Debug.Log("保存HeightMap完成");
    }

    public static void SaveTexture(Texture2D tex, string path)
    {
        byte[] bytes = tex.EncodeToPNG();
        System.IO.File.WriteAllBytes(path, bytes);

        Debug.Log("保存NormalMap完成");
    }

}
